import { BaseService } from '@cool-midway/core';
import { Init, Inject } from '@midwayjs/core';
import { InjectDataSource } from '@midwayjs/typeorm';
import { DataSource } from 'typeorm';

/**
 * 存储过程基础服务
 */
export class ProcedureBaseService extends BaseService {
  @InjectDataSource()
  dataSource: DataSource;

  // 存储过程前缀
  protected procedurePrefix: string;
  // 实体类
  protected entity: any;
  // 是否启用存储过程
  protected enableProcedure = false;

  /**
   * 添加
   */
  async add(param: any) {
    if (this.enableProcedure) {
      const procedureName = `${this.procedurePrefix}add`;
      const params = Object.values(param);
      const sql = `CALL ${procedureName}(${params
        .map((_, i) => '?')
        .join(',')})`;
      return await this.dataSource.query(sql, params);
    }
    return super.add(param);
  }

  /**
   * 删除
   */
  async delete(ids: string) {
    if (this.enableProcedure) {
      const procedureName = `${this.procedurePrefix}delete`;
      const idArray = ids.split(',');
      for (const id of idArray) {
        const sql = `CALL ${procedureName}(?)`;
        await this.dataSource.query(sql, [id]);
      }
      return;
    }
    return super.delete(ids);
  }

  /**
   * 更新
   */
  async update(param: any) {
    if (this.enableProcedure) {
      const procedureName = `${this.procedurePrefix}update`;
      const params = Object.values(param);
      const sql = `CALL ${procedureName}(${params
        .map((_, i) => '?')
        .join(',')})`;
      await this.dataSource.query(sql, params);
      return;
    }
    return super.update(param);
  }

  /**
   * 信息
   */
  async info(id: any, infoIgnoreProperty?: string[]) {
    if (this.enableProcedure) {
      const procedureName = `${this.procedurePrefix}info`;
      const sql = `CALL ${procedureName}(?)`;
      const results = await this.dataSource.query(sql, [id]);
      const result = results[0]?.[0] || null;
      if (result) {
        // 如果指定了忽略属性，则删除这些属性
        if (infoIgnoreProperty) {
          infoIgnoreProperty.forEach(prop => {
            delete result[prop];
          });
        }
      }
      return result;
    }
    return super.info(id, infoIgnoreProperty);
  }

  /**
   * 列表
   */
  async list(query = {}) {
    if (this.enableProcedure) {
      const procedureName = `${this.procedurePrefix}list`;

      // 获取实体的所有列名
      const columns = this.entity.metadata.columns
        .filter(col => !col.isVirtual)
        .map(col => col.databaseName);

      // 构建参数数组，保持与存储过程参数顺序一致
      const params = columns.map(col => query[col] || null);

      // 构建 SQL
      const sql = `CALL ${procedureName}(${params.map(() => '?').join(',')})`;

      // 打印调试信息
      console.log('执行 list 查询：', {
        SQL: sql,
        参数: params,
        原始查询: query,
      });

      const results = await this.dataSource.query(sql, params);
      return results[0] || [];
    }
    return super.list(query, this.entity);
  }

  /**
   * 分页
   */
  async page(query: any) {
    if (this.enableProcedure) {
      const {
        page = 1,
        size = 10,
        sort = 'id',
        order = 'desc',
        ...params
      } = query;
      const procedureName = `${this.procedurePrefix}page`;
      const allParams = [sort, order, page, size];
      const sql = `CALL ${procedureName}(${allParams
        .map((_, i) => '?')
        .join(',')})`;
      const results = await this.dataSource.query(sql, allParams);
      console.log('results', results);
      return {
        test: 1,
        list: results[0] || [],
        pagination: {
          page,
          size,
          total: Number(results[1]?.[0]?.total) || 0,
        },
      };
    }
    return super.page(query, this.entity);
  }
}
